<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>阿里云VOD上传</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <link rel="shortcut icon" href="/static/favicon.ico">
    <script src="/static/js/jquery.min.js?v=2.1.4"></script>
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <script src="/static/layui/layui.2.7.6.js"></script>
    <script src="/static/js/base.js"></script>
</head>

<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-required">选择文件：</label>
                            <div class="layui-upload" style="display: flex;flex-direction: column;">
                                <input type="file" name="file" class="layui-btn upload_video" id="video_upload">
                            </div>
                        </div>
                        <div class="layui-row layui-col-space10 layui-form-item">
                            <div class="layui-col-lg6">
                                <label class="layui-form-label layui-required">视频名称：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="title" lay-verify="required" placeholder="请输入视频名称"
                                           autocomplete="off" class="layui-input" maxlength='60'
                                           value="">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">封面图</label>
                            <div class="layui-input-block">
                                <div class="layui-upload-drag" onclick="upload('thumbnail')">
                                    <i class="layui-icon"></i>
                                    <p>点击上传图片</p>
                                    <div class="layui-hide" id="uploadView">
                                        <hr>
                                        <img src="" alt="上传成功后渲染" style="max-width: 196px">
                                    </div>
                                </div>
                                <input type="hidden" name="cover" value="" autocomplete="off" placeholder=""  class="layui-input">
                                <div class="layui-hide" id="uploadView">
                                    <img src="" alt="上传成功后渲染" style="max-width: 196px">
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">转码清晰度</label>
                            <div class="layui-input-block">
                                <input type="radio" name="quality" value="1" title="标清" >
                                <input type="radio" name="quality" value="2" title="高清" checked>
                                <input type="radio" name="quality" value="3" title="超清" >
                                <input type="radio" name="quality" value="4" title="2K" disabled="">
                            </div>
                        </div>
                        <div class="layui-row layui-col-space10 layui-form-item">
                            <div class="layui-col-lg6">
                                <label class="layui-form-label">简介：</label>
                                <div class="layui-input-block">
                                        <textarea class="layui-textarea" name="desc" placeholder="请输入简介，200字以内"
                                                  style="resize: none;"></textarea>
                                </div>
                            </div>
                        </div>
                        <div  id="win" style="display:block" class="layui-row layui-col-space10 layui-form-item">
                            <div class="layui-col-lg6">
                                <label class="layui-form-label">上传进度：</label>
                                <div class="layui-input-block">
                                    <div style="margin-top: 10px" class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="progressBar">
                                        <div class="layui-progress-bar layui-bg-gree" lay-percent="0%"></div>
                                    </div>
                                </div>

                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button type="button" class="layui-btn" id="submit" lay-submit lay-filter="mySubmit">提交</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="/static/aliyun-upload-sdk-1.5.3/aliyun-upload-sdk-1.5.3.min.js"></script>
<script src="/static/aliyun-upload-sdk-1.5.3/lib/es6-promise.min.js"></script>
<script src="/static/aliyun-upload-sdk-1.5.3/lib/aliyun-oss-sdk-6.17.1.min.js"></script>
<script>
    //兼容IE11
    if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function (fileData) {
            var binary = "";
            var pt = this;
            var reader = new FileReader();
            reader.onload = function (e) {
                var bytes = new Uint8Array(reader.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }
                //pt.result  - readonly so assign binary
                pt.content = binary;
                pt.onload()
            }
            reader.readAsArrayBuffer(fileData);
        }
    }
    var uploader = null,file,env,userid

    layui.config({
        base: '/static/admin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'upload', 'table', 'tree', 'element'], function () {
        var $ = layui.$
            , upload = layui.upload,
            form = layui.form,
            tree = layui.tree,
            element = layui.element,
            table = layui.table;
        element.init();

        $.ajax({
            url: '/admin/vod/getConfig',
            type: 'get',
            async:false,
            headers:{
                'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                'accept':'*/*'
            },
            success: function (res) {

                if (res.code == 1) {
                    var data = res.data
                    env = data.env
                    userid = data.user_id
                }else{
                    layer.msg(res.msg)
                }
            }, error: function () {
                layer.closeAll();
                layer.msg('网络连接失败');
            }
        })

        $('#video_upload').on('change', function (e) {

            file = e.target.files[0]
            if (!file) {
                alert("请先选择需要上传的文件!")
                return
            }

            var title = file.name.split('.')
            console.log('======',title[0])
            $('input[name=title]').attr('value',title[0])
        })


        let flag = true
        form.on('submit(mySubmit)', function (data) {
            var field = data.field;
            if (!field.file) {
                layer.alert("请先选择需要上传的文件!")
                return
            }

            //userData = '{"Vod":{"MessageCallback":{"CallbackURL":"http://dev-music.quanyinzi.com/vod/notify"},"Extend":{"env":"dev","test":"www"}}}';
            userData = '{"Vod":{}}'
            uploader = createUploader(field)

            uploader.addFile(file, null, null, null, userData)

            var first_load = layer.load(0, {
                shade: [0.1, '#000'] //0.1透明度的白色背景
            });
            console.log('uploadd==',uploader)
            layer.msg('文件检查中...')
            setTimeout(function () {
                if(flag){
                    uploader.startUpload()
                }else{
                    layer.closeAll('loading');
                }
            },2000)

        });

        function createUploader(field) {
            var uploadVod = new AliyunUpload.Vod({
                // 默认参数
                timeout: 60000,
                partSize: 1048576,
                parallel: 5,
                retryCount: 3,
                retryDuration: 2,
                region: 'cn-shanghai',
                userId: userid,
                // 添加文件成功
                addFileSuccess: function (uploadInfo) {
                    console.log('addFileSuccess--uploadInfo:', uploadInfo)
                    // $.ajax({
                    //     url: '/admin/vod/checkExist',
                    //     data: {
                    //         'fileHash': uploadInfo.fileHash,
                    //         'quality': field.quality
                    //     },
                    //     async: false,
                    //     success: function (res) {
                    //         console.log(1, res)
                    //         if (res.code == 0) {
                    //             flag = false
                    //             layer.alert(res.msg)
                    //             return false
                    //         }else{
                    //             flag = true
                    //         }
                    //
                    //
                    //     },
                    //     error: function () {
                    //         layer.closeAll();
                    //         layer.msg('网络连接失败');
                    //     }
                    // })
                    // console.log(11)

                },
                // 开始上传
                onUploadstarted: function (uploadInfo) {
                    let userData={};
                    userData.env=env
                    userData.host=window.location.host

                    $.ajax({
                        url: '/admin/vod/getUploadAuth',
                        type: 'post',
                        data:{
                            'quality':field.quality,
                            'title' : field.title,
                            'desc' : field.desc,
                            'cover' : field.cover,
                            'fileName':uploadInfo.file.name,
                            'userData':userData
                        },
                        async:false,
                        headers:{
                            'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                            'accept':'*/*'
                        },
                        success: function (res) {
                            console.log(3)
                            console.log(res)
                            console.log(uploadInfo);
                            console.log(res.data.UploadAuth);
                            console.log(res.data.UploadAddress);
                            console.log(res.data.videoId);
                            uploader.setUploadAuthAndAddress(uploadInfo, res.data.UploadAuth, res.data.UploadAddress,res.data.videoId)
                            if (res.code == 1 && res.data.exist) {
                                layer.msg(res.msg)
                            }else{
                                layer.msg(res.msg)
                            }
                        }, error: function () {
                            layer.closeAll();
                            layer.msg('网络连接失败');
                        }
                    })
                },
                // 文件上传成功
                onUploadSucceed: function (uploadInfo) {
                    console.log('文件上传成功')
                    console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
                    console.log(uploadInfo)
                    layer.closeAll('loading');
                    fileExt = uploadInfo.file.type.split('/')
                    $.ajax({
                        url:"/admin/vod/upload",
                        type:"POST",
                        dataType: 'json',
                        data:{
                            'fileHash' : uploadInfo.fileHash,
                            'videoId' : uploadInfo.videoId,
                            'title' : field.title,
                            'cover' : field.cover,
                            'desc' : field.desc,
                            'fileName':uploadInfo.file.name,
                            'size':uploadInfo.file.size,
                            'ext':fileExt[1],
                            'quality':field.quality
                        },
                        async:false,
                        headers:{
                            'token':localStorage.getItem('hypercmfname')+'_'+localStorage.getItem('token'),
                            'accept':'*/*'
                        },
                        success:function(res){
                            console.log('+++====',res)
                            if(res.code==1){
                                setTimeout(function () {
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);
                                    parent.layui.table.reload('dataTable');
                                }, 200);
                            }else{
                                layer.msg(res.msg)
                            }
                        },
                        fail:function(){
                            layer.msg('网络异常')
                        }
                    })
                },
                // 文件上传失败
                onUploadFailed: function (uploadInfo, code, message) {
                    console.log('文件上传失败')
                    console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
                },
                // 取消文件上传
                onUploadCanceled: function (uploadInfo, code, message) {
                    console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
                },
                // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
                onUploadProgress: function (uploadInfo, totalSize, progress) {
                    console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
                    var progressPercent = Math.ceil(progress * 100)
                    element.progress('progressBar',progressPercent  + '%')
                    console.log('文件上传中')
                },
                // 上传凭证超时
                onUploadTokenExpired: function (uploadInfo) {
                    // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                    // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                    // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                    //$('#status').text('文件上传超时!')
                    console.log('文件上传超时')
                    let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
                    $.get(refreshUrl, function (data) {
                        var uploadAuth = data.UploadAuth
                        uploader.resumeUploadWithAuth(uploadAuth)
                        console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
                    }, 'json')
                },
            //     "http://outin-4474e9eced4d11ec935300163e1c7426.oss-cn-shanghai.aliyuncs.com/customerTrans/61891e694035c1a39b65261dd2fa2cdf/4b91ae70-1862b61b2b4-0006-0ea4-4b5-9b510.mp4"
            //     https://vod.quanyinzi.com/8f4878a0f09871eda0fe6723b78e0102/4bf6123949c94ea0b87aaf09e1e48124-bc88928af415273cfdbd2e2ac4d4a516-ld.m3u8
            //     https://vod.quanyinzi.com/8f4878a0f09871eda0fe6723b78e0102/4bf6123949c94ea0b87aaf09e1e48124-44c508740a2ed5aac5a02d90e68123f4-ld.m3u8
            // https://vod.quanyinzi.com/customerTrans/2279b87e3ae161a5b59dbffbd349266c/257ed5a9-1880ee95cf4-0006-0ea4-4b5-9b510.mp4
            //     "http://vod.quanyinzi.com/abdeb0e0a6d071eda8420675b3ed0102/859641a721da4aa1a43c33f2976bce97-b88e1baf12279197553605df1104e811-sd.m3u8"
                // 全部文件上传结束
                onUploadEnd: function (e) {
                    //$('#status').text('文件上传完毕!')
                    console.log('文件上传完毕',e)
                    console.log("onUploadEnd: uploaded all the files")
                }
            });

            return uploadVod;
        }

    })
    function upload(from=''){
        layui.layer.open({
            title: '选择图片',
            type: 2,
            shadeClose:true,
            area: ['90%','90%'],
            content: '/admin/public/image_list.html?from='+from
        })
    }
    //layer弹出的子页面传值到当前页面
    function GetChildValue(data,from=''){
        if(from == 'video'){
            $("input[name=video]").attr("value",data[0].id)
        }else if(from == 'thumbnail'){
            console.log(from,data)

            $("input[name=cover]").attr("value",data[0].url)
            layui.$('#uploadView').removeClass('layui-hide').find('img').attr('src', data[0].url);
        }
    }
    function showBigImage(e) {
        if ($(e).attr('src') == "\\static\\common\\images\\plus.png") {
            return false;
        }
        var width = $(e)[0].naturalWidth;
        var height = $(e)[0].naturalHeight;
        var max = 600;
        if (width > max) {
            height = height * (max / width);
            width = max;
        }
        if (height > max) {
            width = width * (max / height);
            height = max;
        }
        console.log(width, height);
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true, //点击阴影关闭
            area: [width + 'px', height + 'px'], //宽高
            content: "<img width='100%' src=" + $(e).attr('src') + " />"
        });
    }

    function formatSecond(second) {
        var forMatDate = '';
        var hours = Math.floor((second % 86400) / 3600);
        var minutes = Math.floor(((second % 86400) % 3600) / 60);
        var seconds = Math.floor(((second % 86400) % 3600) % 60);
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }
        if (hours == 0) {
            forMatDate = minutes + ":" + seconds;
        } else {
            forMatDate = hours + ":" + minutes + ":" + seconds;
        }
        return forMatDate;
    }

</script>

</html>